import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { Login } from '@a/account'
import { setToken, setUsername, getUsername, getToken } from '@u/cookies';
import { Logout } from '@/api/account';
import { removeToken, removeUsername } from '@/utils/cookies';


export const useAppStore = defineStore('app', () => {
  const collapse = ref(JSON.parse(sessionStorage.getItem('collapse')) || false);
  const token = ref("" || getToken());
  const username = ref("" || getUsername());
  const switchAside = () => {
    collapse.value = !collapse.value;
    sessionStorage.setItem('collapse', JSON.stringify(collapse.value))
  }
  const login = (requestData) => {
    return new Promise((resolve, reject) => {
      Login(requestData).then(res => {
        let data = res.data;
        SET_TOKEN(data.token)
        SET_USERNAME(data.username)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }
  const logout = () => {
    return new Promise((resolve, reject) => {
      Logout().then(res => {
        removeToken()
        removeUsername()
        token.value = ""
        username.value = ""
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }
  const SET_TOKEN = (_value) => {
    token.value = _value;
    _value && setToken(_value)
  }
  const SET_USERNAME = (_value) => {
    username.value = _value;
    _value && setUsername(_value)
  }

  return { login, logout, collapse, username, token, switchAside, SET_TOKEN, SET_USERNAME }
})
